/* 
 *封装登录模块，默认获取用户公开信息等
 *使用必须配合现有模块集成的PHP和数据库文件
 *两个参数都为必选，num为手机号，fn为回调函数
 *不需要手机号登录时，手机号可以写为num=''
 */
function login(app, fn) {
	uni.login({
		success: function(e) {
			var path = '/xyb/user/third';
			var data = {
				code: e.code
			}
			requestPost(app, path, data, function(res) {
				if (res.data.code == 1) {
					uni.setStorageSync('local_user_session', res.data.data.token);
					app.globalData.openUserInfo = res.data.data.token;
					fn(res);
				} else if (res.data.status == 'fail') {
					uni.showModal({
						title: '服务器繁忙',
						content: '服务器繁忙，请稍后再试！',
						showCancel: false
					})
				}
			});
		},
		fail: function(e) {
			console.log(e)
			uni.hideToast();
			uni.showModal({
				title: '系统错误',
				content: '发生了系统错误，请您稍后再试！',
				showCancel: false
			})
		},

	})
}
/*
 *网络请求API封装
 *参数全部为必选参数
 *用于无需登录的网络请求
 */
function request(app, path, data, fn) {
	var url = app.globalData.adminPath + path;
	uni.request({
		url: url,
		data: data,
		header: {
			"Content-Type": "application/x-www-form-urlencoded"
		},
		method: 'GET',
		success: function(res) {
			// result(res.data);
			fn(res);
		},
		fail: function(res) {
			//调用接口失败或回传失败
			uni.showModal({
				title: '服务器繁忙',
				content: '服务器繁忙或网络不稳定，请稍后再试！'
			})
		},
	})
}

function requestPost(app, path, data, fn) {
	var url = app.globalData.adminPath + path;
	if (app.globalData.default_agent) {
		data.agent_id = app.globalData.default_agent.id || '';
	}
	uni.request({
		url: url,
		data: data,
		header: {
			"Content-Type": "application/x-www-form-urlencoded"
		},
		method: 'POST',
		success: function(res) {
			// result(res.data);
			fn(res);
		},
		fail: function(res) {
			//调用接口失败或回传失败
			uni.showModal({
				title: '服务器繁忙',
				content: '服务器繁忙或网络不稳定，请稍后再试！'
			})
		},
	})
}

//判断登录状态，并自动进入相应登录逻辑
function loginCheck(app, fn) {
	//先判断平台
	if (app.globalData.appPlat == 'MP-WEIXIN') {
		//小程序平台，进行小程序平台相关登录逻辑
		//先判断登录是否有效
		uni.checkSession({
			success() {
				//session_key未过期
				if (app.globalData.openUserInfo) {
					fn();
				} else {
					login(app, function(res) {
						loginCheck(app, fn);
					});
				}
			},
			fail() {
				// session_key 已经失效
				login(app, function(res) {
					loginCheck(app, fn)
				})
			}
		})
	} else if (app.globalData.appPlat == 'APP-PLUS' || app.globalData.appPlat == 'H5') {
		//进行APP或H5页面的判断逻辑
		if (app.globalData.openUserInfo) {
			fn();
		} else {
			uni.navigateTo({
				url: '/pages/Component/Module/Login/loginsms/login'
			});
		}

	} else if (app.globalData.appPlat == 'MP-WEIXIN-H5') {
		//进行微信公众号判断逻辑
		if (app.globalData.openUserInfo) {
			fn();
		} else {

		}

	}
}

function post(app, path, data, fn) {
	//先判断平台
	if (app.globalData.appPlat == 'MP-WEIXIN') {
		//小程序平台，进行小程序平台相关登录逻辑
		//先判断登录是否有效
		if (uni.getStorageSync('local_user_session')) {
			//session_key未过期
			var url = app.globalData.adminPath + path;
			data.app_plat = app.globalData.appPlat;
			if (app.globalData.default_agent) {
				data.agent_id = app.globalData.default_agent.id || '';
			}
			data.token = uni.getStorageSync('local_user_session');
			uni.request({
				url: url,
				header: {
					"Content-Type": "application/x-www-form-urlencoded"
				},
				data: data,
				method: 'POST',
				success: function(res) {
					result(res.data);
					//判断登录是否失效
					if (res.data.code == '401') {
						login(app, function(res) {
							post(app, path, data, fn);
						})
					} else if (res.data.state == 'Login_Basic') {
						//关闭加载
						uni.hideLoading();
						//进入资料完善页面
						uni.$once('sys_user_reginfo', function(result) {
							//完善成功后，重新执行
							if (data.loading) {
								uni.showLoading({
									title: data.loading
								});
							}
							post(app, path, data, fn);
						})
						uni.navigateTo({
							url: '/pages/Component/Module/Login/reg/reg'
						});
					} else {
						fn(res);
					}

				},
				fail: function(res) {
					//调用接口失败或回传失败
					uni.showModal({
						title: '服务器繁忙',
						content: '服务器繁忙或网络不稳定，请稍后再试！'
					})
				},
			})

		} else {
			uni.redirectTo({
				url: "/pages/login/index"
			})
		}

	} else if (app.globalData.appPlat == 'APP-PLUS' || app.globalData.appPlat == 'H5') {
		//进行APP或H5页面的通讯逻辑
		var url = app.globalData.adminPath + path;
		data.appkey = app.globalData.appKey;
		data.father_appkey = app.globalData.appFormerKey;
		data.app_vision = app.globalData.appVision;
		data.app_plat = app.globalData.appPlat;
		if (app.globalData.openUserInfo) {
			data.trd_session = app.globalData.openUserInfo;
		}
		uni.request({
			url: url,
			header: {
				"Content-Type": "application/x-www-form-urlencoded"
			},
			data: data,
			method: 'POST',
			success: function(res) {
				result(res.data);
				//判断登录是否失效
				if (res.data.state == 'Login_Expired') {
					//关闭加载
					uni.hideLoading();
					//清空本地缓存信息
					app.globalData.user_openinfo = '';
					uni.removeStorageSync('local_user_session');
					//进入登录页面
					uni.$once('sys_user_loginin', function(result) {
						//登录成功后，重新执行
						if (data.loading) {
							uni.showLoading({
								title: data.loading
							});
						}
						post(app, path, data, fn);
					})
					uni.navigateTo({
						url: '/pages/Component/Module/Login/loginsms/login'
					});
				} else {
					fn(res);
				}
			},
			fail: function(res) {
				//调用接口失败或回传失败
				uni.showModal({
					title: '服务器繁忙',
					content: '服务器繁忙或网络不稳定，请稍后再试！'
				})
			},
		})
	} else if (app.globalData.appPlat == 'MP-WEIXIN-H5') {
		//进行微信公众号通讯
		var url = app.globalData.adminPath + path;
		data.appkey = app.globalData.appKey;
		data.father_appkey = app.globalData.appFormerKey;
		data.app_vision = app.globalData.appVision;
		data.app_plat = app.globalData.appPlat;
		if (app.globalData.openUserInfo) {
			data.trd_session = app.globalData.openUserInfo;
		}
		uni.request({
			url: url,
			header: {
				"Content-Type": "application/x-www-form-urlencoded"
			},
			data: data,
			method: 'POST',
			success: function(res) {
				result(res.data);
				//判断登录是否失效
				if (res.data.state == 'Login_Expired') {

				} else if (res.data.state == 'Login_Basic') {
					//关闭加载
					uni.hideLoading();
					//进入资料完善页面
					uni.$once('sys_user_reginfo', function(result) {
						//完善成功后，重新执行
						if (data.loading) {
							uni.showLoading({
								title: data.loading
							});
						}
						post(app, path, data, fn);
					})
					uni.navigateTo({
						url: '/pages/Component/Module/Login/reg/reg'
					});
				} else {
					fn(res);
				}

			},
			fail: function(res) {
				//调用接口失败或回传失败
				uni.showModal({
					title: '服务器繁忙',
					content: '服务器繁忙或网络不稳定，请稍后再试！'
				})
			},
		})
	}
}

function gets(app, path, data, fn) {
	//先判断平台
	if (app.globalData.appPlat == 'MP-WEIXIN') {
		//先判断登录是否有效
		uni.checkSession({
			success() {
				//session_key未过期
				var url = app.globalData.adminPath + path;
				data.app_plat = app.globalData.appPlat;
				if (app.globalData.default_agent) {
					data.agent_id = app.globalData.default_agent.id || '';
				}
				if (app.globalData.openUserInfo) {
					data.token = app.globalData.openUserInfo;
					uni.request({
						url: url,
						data: data,
						header: {
							"Content-Type": "application/x-www-form-urlencoded"
						},
						method: 'GET',
						success: function(res) {
							result(res.data);
							//判断登录是否失效
							if (res.data.code == '401') {
								login(app, function(res) {
									gets(app, path, data, fn);
								})
							} else if (res.data.state == 'Login_Basic') {
								//关闭加载
								uni.hideLoading();
								//进入资料完善页面
								uni.$once('sys_user_reginfo', function(result) {
									//完善成功后，重新执行
									if (data.loading) {
										uni.showLoading({
											title: data.loading
										});
									}
									gets(app, path, data, fn);
								})
								uni.navigateTo({
									url: '/pages/Component/Module/Login/reg/reg'
								});
							} else {
								fn(res);
							}
						},
						fail: function(res) {
							//调用接口失败或回传失败
							uni.showModal({
								title: '服务器繁忙',
								content: '服务器繁忙或网络不稳定，请稍后再试！'
							})
						},
					})
				} else {
					login(app, function(res) {
						gets(app, path, data, fn);
					})
				}
			},
			fail() {
				// session_key 已经失效
				login(app, function(res) {
					gets(app, path, data, fn);
				})
			}
		})

	} else if (app.globalData.appPlat == 'APP-PLUS' || app.globalData.appPlat == 'H5') {
		var url = app.globalData.adminPath + path;
		data.appkey = app.globalData.appKey;
		data.father_appkey = app.globalData.appFormerKey;
		data.app_vision = app.globalData.appVision;
		data.app_plat = app.globalData.appPlat;
		if (app.globalData.openUserInfo) {
			data.trd_session = app.globalData.openUserInfo;
		}
		uni.request({
			url: url,
			data: data,
			method: 'GET',
			success: function(res) {
				result(res.data);
				//判断登录是否失效
				if (res.data.state == 'Login_Expired') {
					//关闭加载
					uni.hideLoading();
					//清空本地缓存信息
					app.globalData.user_openinfo = '';
					uni.removeStorageSync('local_user_session');
					//前往登录页面
					uni.$once('sys_user_loginin', function(result) {
						//登录成功后，重新执行
						if (data.loading) {
							uni.showLoading({
								title: data.loading
							});
						}
						gets(app, path, data, fn);
					})
					uni.navigateTo({
						url: '/pages/Component/Module/Login/loginsms/login'
					});
				} else {
					fn(res);
				}
			},
			fail: function(res) {
				//调用接口失败或回传失败
				uni.showModal({
					title: '服务器繁忙',
					content: '服务器繁忙或网络不稳定，请稍后再试！'
				})
			},
		})
	} else if (app.globalData.appPlat == 'MP-WEIXIN-H5') {
		//微信公众号
		var url = app.globalData.adminPath + path;
		data.appkey = app.globalData.appKey;
		data.father_appkey = app.globalData.appFormerKey;
		data.app_vision = app.globalData.appVision;
		data.app_plat = app.globalData.appPlat;
		if (app.globalData.openUserInfo) {
			data.trd_session = app.globalData.openUserInfo;
		}
		uni.request({
			url: url,
			data: data,
			method: 'GET',
			success: function(res) {
				result(res.data);
				//判断登录是否失效
				if (res.data.state == 'Login_Expired') {

				} else if (res.data.state == 'Login_Basic') {
					//关闭加载
					uni.hideLoading();
					//进入资料完善页面
					uni.$once('sys_user_reginfo', function(result) {
						//完善成功后，重新执行
						if (data.loading) {
							uni.showLoading({
								title: data.loading
							});
						}
						gets(app, path, data, fn);
					})
					uni.navigateTo({
						url: '/pages/Component/Module/Login/reg/reg'
					});
				} else {
					fn(res);
				}
			},
			fail: function(res) {
				//调用接口失败或回传失败
				uni.showModal({
					title: '服务器繁忙',
					content: '服务器繁忙或网络不稳定，请稍后再试！'
				})
			},
		})

	}
}
/*
 *网络上传API封装
 *参数全部为必选参数
 *path格式为：控制器名/方法名，data为传递的数据对象，默认不需要添加appkey等数据
 *当islogin取值为true时，会默认发送appkey和trd_session数据，并对用户登录状态进行自动验证
 *当islogin取值为false时，会默认只发送appkey，不对用户登录状态做任何验证，用于通用请求
 *file_name文件对应的 key , 开发者在服务器端通过这个 key 可以获取到文件二进制内容
 *file_path为文件的微信临时路径
 */
function upload(app, path, data, file_name, file_path, fn) {
	if (uni.getStorageSync('local_user_session')) {
		//session_key未过期
		var url = app.globalData.adminPath + path;
		data.app_plat = app.globalData.appPlat;
		data.agent_id = app.globalData.default_agent.id;

		data.token = app.globalData.openUserInfo;
		uni.uploadFile({
			url: url,
			filePath: file_path,
			name: file_name,
			formData: data,
			success: function(res) {
				result(res.data);
				//判断登录是否失效
				if (res.data.state == 'Login_Expired') {
					login(app, function(res) {
						upload(app, path, data, file_name, file_path, fn);
					});
				} else {
					fn(res);
				}
			},
			fail: function(res) {
				console.log(res)
				//调用接口失败或回传失败
				uni.showModal({
					title: '系统错误',
					content: res.errMsg,
					cancle: false
				})
			},
		})

	} else {
		uni.redirectTo({
			url: "/pages/login/index"
		})
	}


}
/*
 *网络上传图片到系统图库封装
 *参数全部为必选参数
 *user_id-上传图片的用户id
 *file_name-图片名称
 *file_path-图片临时路径
 */
function upimg(app, user_id, file_name, file_path, fn) {
	var url = app.globalData.adminImg.path + '?param=' + app.globalData.appKey;
	var data = {
		user_id: user_id,
		path: app.globalData.adminImg.folder
	}
	uni.uploadFile({
		url: url,
		filePath: file_path,
		name: file_name,
		formData: data,
		success: function(res) {
			res.data = JSON.parse(res.data);
			console.log(res.data);
			if (res.data.status == 'success') {
				//上传成功，返回结果
				fn(res);
			} else {
				uni.hideLoading();
				if (res.data.status == 'illegal') {
					uni.showModal({
						title: '图片违规',
						content: '您上传的图片涉嫌违规，请重新选择合法图片！',
						cancle: false
					})
				} else if (res.data.status == 'not_enough') {
					uni.showModal({
						title: '空间不足',
						content: '服务器空间不足，请稍后再试！',
						cancle: false
					})
				} else if (res.data.status == 'data_error') {
					uni.showModal({
						title: '系统错误',
						content: '请重启微信或小程序，然后重试！',
						cancle: false
					})
				} else if (res.data.status == 'fail' && res.data.info) {
					uni.showModal({
						title: '图片错误',
						content: res.data.info,
						cancle: false
					})
				} else {
					uni.showModal({
						title: '系统繁忙',
						content: '服务器繁忙，请您稍后再试！',
						cancle: false
					})
				}
			}

		},
		fail: function(res) {
			//调用接口失败或回传失败
			uni.showModal({
				title: '系统错误',
				content: '系统发生错误，请您稍后再试！',
				cancle: false
			})
		},
	})

}

//判断小程序状态
function result(res) {
	res = res || {};
	if (res.state == 'ERROR') {
		uni.redirectTo({
			url: '/pages/Home/error/error?title=小程序出错啦！&content=请联系小程序运营官方！'
		})
		return false;
	} else if (res.state == 'TIMEOUT') {
		uni.redirectTo({
			url: '/pages/Home/error/error?title=小程序出错啦！&content=请您联系小程序运营官方！'
		})
		return false;
	} else if (res.state == 'APP_CLOSE') {
		uni.redirectTo({
			url: '/pages/Home/error/error?title=小程序出错啦！&content=请您联系小程序运营官方！'
		})
		return false;
	} else if (res.state == 'SYSTEM_CLOSE') {
		uni.redirectTo({
			url: '/pages/Home/error/error?title=系统维护中&content=系统正在升级维护，请您稍后重启小程序进入！'
		})
		return false;
	} else {
		//不做任何动作
		return true;
	}
}

function ikzGetLocalUrl() {
	var local_url = window.location.href;
	local_url = local_url.replace('http://', '');
	local_url = local_url.replace('https://', '');
	var url_pos = local_url.indexOf("/");
	local_url = local_url.slice(url_pos);
	return '/aaa';
}
//模块输出类
module.exports.post = post;
module.exports.get = gets;
module.exports.request = request;
module.exports.requestPost = requestPost;
module.exports.up = upload;
module.exports.upimg = upimg;
module.exports.loginCheck = loginCheck;